package com.binguo.common.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class MultipartFileUtil {

    private static final Logger logger = LoggerFactory.getLogger(MultipartFileUtil.class);

    public static String uploadFile(MultipartFile file){
        logger.info("进入uploadFile方法");
        String uplocdFolder ="D:\\uploadFolder";
        //String fileUrl ="http://192.168.1.166:8088";
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //获取文件名后缀
        Calendar currTime = Calendar.getInstance();
        //获取文件名后缀
        String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf("."));
        suffix = suffix.toLowerCase();
        //给文件重命名确保唯一
        fileName = UUID.randomUUID().toString()+suffix;
        File targetFile = new File(uplocdFolder, fileName);
        if(!targetFile.getParentFile().exists()){    //注意，判断父级路径是否存在
            targetFile.getParentFile().mkdirs();
        }
        long size = 0;
        //保存
        try {
            file.transferTo(targetFile);
            size = file.getSize();
            logger.info("文件保存成功,保存路径:"+uplocdFolder+"文件大小:"+size);
            return uplocdFolder + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
